package com.zb.util;

import com.ZLHW.base.Exception.BaseErrorModel;
import org.apache.commons.lang.BooleanUtils;
import org.apache.commons.lang.math.NumberUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

/**
 * Created by Administrator on 2014/9/29.
 */
public class MapUtils {
    public static int getInt(Map<String,String> map,String key,int defaultval){
        String val = map.get(key);
        if(NumberUtils.isNumber(val)){
            return NumberUtils.createInteger(val);
        }else {
            return defaultval;
        }
    }

    public static int getInt(Map<String,String> map,String key,String errorinfo){
        String val = map.get(key);
        if(NumberUtils.isNumber(val)){
            return NumberUtils.createBigDecimal(val).intValue();
        }else {
           throw new BaseErrorModel(errorinfo,"");
        }
    }

    public static long getLong(Map<String,String> map,String key,String errorinfo){
        String val = map.get(key);
        if(NumberUtils.isNumber(val)){
            return NumberUtils.createBigDecimal(val).longValue();
        }else {
            throw new BaseErrorModel(errorinfo,"");
        }
    }

    public static String getString(Map<String,String> map,String key,String errorinfo){
        String val = map.get(key);
        if(StringUtils.isNotBlank(val)){
            return val;
        }else {
            throw new BaseErrorModel(errorinfo,"");
        }
    }

    public static Date getDate(Map<String,String> map,String key,String errorinfo){
        SimpleDateFormat dateformat1=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String val = map.get(key);
        if(StringUtils.isNotBlank(val)){
            try {
                Date date = dateformat1.parse(val.replace("T", " "));
                return date;
            } catch (ParseException e) {
                throw new BaseErrorModel(errorinfo,"");
            }
        }else {
            throw new BaseErrorModel(errorinfo,"");
        }
    }

    public static boolean getBoolen(Map<String,String> map,String key,String errorinfo){
        String val = map.get(key);
        if(StringUtils.isBlank(val)){
            throw new BaseErrorModel(errorinfo,"");
        }
        return BooleanUtils.toBoolean(map.get(key));
    }
}
